﻿<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Serail Passthrough Tool</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            height: 100vh;
            background-color: #f7f7ff;
        }

        div {
            height: calc(100% - 4rem);
            padding: 2rem;
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            grid-template-rows: 2rem 1fr;
            row-gap: 1rem;
            column-gap: 2rem;
        }

        div_child {
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-template-rows: 2rem 0fr;
            row-gap: 1rem;
            column-gap: 2rem;
        }

        textarea {
            resize: none;
            overflow-y: scroll;
            overflow-x: hidden;
            padding: 1rem;
        }
    </style>
    <script>
        function getBroswer() {
            var sys = {};
            var ua = navigator.userAgent.toLowerCase();
            var s;
            (s = ua.match(/edge\/([\d.]+)/)) ? sys.edge = s[1] :
                (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] :
                    (s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
                        (s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
                            (s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
                                (s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
                                    (s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;

            if (sys.edge) return { broswer: "Edge", version: sys.edge };
            if (sys.ie) return { broswer: "IE", version: sys.ie };
            if (sys.firefox) return { broswer: "Firefox", version: sys.firefox };
            if (sys.chrome) return { broswer: "Chrome", version: sys.chrome };
            if (sys.opera) return { broswer: "Opera", version: sys.opera };
            if (sys.safari) return { broswer: "Safari", version: sys.safari };

            return { broswer: "", version: "0" };
        }
        if (!('serial' in navigator)) {
            alert('当前浏览器不支持 Web Serial API串口操作,请更换Edge或Chrome浏览器')
        } else {
            var abc = getBroswer();
            alert("broswer:" + abc.broswer + " version:" + abc.version)
        }
    </script>
</head>

<body>
    <div>
        <div_child>
            <button id="btnOpen">open</button>
            <button id="btnClose">close</button>
        </div_child>
        <button id="btnSend">send</button>
        <button id="btnClear">clear</button>
        <textarea id="iptLog" readonly></textarea>
        <textarea id="iptOutput">7c ff ff 82 32 00 d2</textarea>
        <textarea id="iptInput" readonly></textarea>
    </div>
    <script>
        const btnOpen = document.querySelector("#btnOpen");
        const btnClose = document.querySelector("#btnClose");
        const btnSend = document.querySelector("#btnSend");
        const btnClear = document.querySelector("#btnClear");
        const iptLog = document.querySelector("#iptLog");
        const iptOutput = document.querySelector("#iptOutput");
        const iptInput = document.querySelector("#iptInput");

        iptLog.value += "Serial Passthrough Tool\n\n";
        iptLog.value += "This is an Serial Passthrough device read/write Tool.\n\n";
        iptLog.value += "Device must have one collection with one input and one output.\n\n";
        iptLog.value += "For more detail see below:\n\n";

        let port = null;
        let reader = null;
        let reading = false;

        // 打开设备相关操作
        btnOpen.onclick = async () => {
            try {
                port = await navigator.serial.requestPort(); // 弹出系统串口列表对话框，选择一个串口进行连接

                //let ports = await navigator.serial.getPorts(); // 获取已连接的授权过的设备列表

                // const devices = await navigator.hid.requestDevice({
                //     filters: [{
                //         vendorId: 0xabcd,  // 根据VID进行过滤
                //         productId: 0x1234, // 根据PID进行过滤
                //         usagePage: 0x0c,   // 根据usagePage进行过滤
                //         usage: 0x01,       // 根据usage进行过滤
                //     },],
                // });

                if (port === null) {
                    iptLog.value += "No device selected\n\n";
                    iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
                    return;
                }

                await port.open({
                    baudRate: 57600,
                    // bufferSize: 255,   // 读写缓存，默认255
                    // dataBits: 8,       // 数据位，默认8
                    // flowControl: none, // 流控制，默认无
                    // parity: none,      // 校验，默认无
                    // stopBits: 1,       // 停止位，默认1
                });
                document.getElementById('btnOpen').disabled = true;
                document.getElementById('btnClose').disabled = false;
                listenReceived();
                iptLog.value += "Port opened\n\n";
                iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部

            } catch (error) {
                iptLog.value += `${error}\n\n`;
                iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
            }
        };

        function updateInputData(data) {
            let array = new Uint8Array(data); // event.data.buffer就是接收到的inputreport包数据了
            let hexstr = "";
            for (const data of array) {
                hexstr += (Array(2).join(0) + data.toString(16).toUpperCase()).slice(-2) + " "; // 将字节数据转换成（XX ）形式字符串
            }
            iptInput.value += hexstr;
            iptInput.scrollTop = iptInput.scrollHeight; // 滚动到底部

            iptLog.value += `Received ${data.byteLength} bytes\n\n`;
            iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
        }

        // 读取数据
        async function listenReceived() {
            if (reading) {
                console.log("On reading.");
                return;
            }
            reading = true;

            while (port.readable && reading) {
                reader = port.readable.getReader();
                try {
                    while (true) {
                        const { value, done } = await reader.read();
                        if (done) {
                            // |reader| has been canceled.
                            break;
                        }
                        // 需要特别注意的是：实际使用中即使对端是按一个个包发送的串口数据，接收时收到的也可能是分多段收到的
                        updateInputData(value);
                    }
                } catch (e) {
                    console.log(e);
                } finally {
                    reader.releaseLock();
                }
            }

            await port.close(); // 关闭串口
            //await port.forget(); // 取消授权
            port = null;
            console.log("Port closed.");
            iptLog.value += "Port opened\n\n";
            iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
        }

        // 关闭串口
        btnClose.onclick = async () => {
            if ((port === null) || (!port.writable)) {
                console.log("Not opened.");
                return;
            }

            if (reading) {
                reading = false;
                reader?.cancel();
            }
            document.getElementById('btnOpen').disabled = false;
            document.getElementById('btnClose').disabled = true;
        }

        // 获取发送窗口十六进制字符串转换为字节数组
        function getOutputData() {
            let outputDatastr = iptOutput.value.replace(/\s+/g, ""); // 去除所有空白字符
            if (outputDatastr.length % 2 == 0 && /^[0-9a-fA-F]+$/.test(outputDatastr)) {
                // 获取字节数组长度
                const byteLength = outputDatastr.length / 2;
                // 创建字节数组
                const outputData = new Uint8Array(byteLength);
                // 将字符串转成字节数组数据
                for (let i = 0; i < byteLength; i++) {
                    outputData[i] = parseInt(outputDatastr.substr(i * 2, 2), 16);
                }
                // 返回数据
                return outputData;
            } else {
                throw "Data is not even or 0-9、a-f、A-F";
            }
        }

        // 发送数据相关操作
        btnSend.onclick = async () => {
            if ((port === null) || (!port.writable)) {
                console.log("Not opened.");
                return;
            }
            const writer = port.writable.getWriter();
            await writer.write(getOutputData()); // 发送数据
            writer.releaseLock();

            iptLog.value += `Send ${getOutputData().length} bytes\n\n`;
            iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
        };

        // 全局串口设备插入事件
        navigator.serial.onconnect = (event) => {
            console.log("Serial port connected: ", event.target);
            iptLog.value += `Serial port connected:\n${event.device.productName}\nPID ${event.device.productId} VID ${event.device.vendorId}\n\n`;
            iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
        };

        // 全局串口设备拔出事件
        navigator.serial.ondisconnect = (event) => {
            console.log("Serial port disconnected: ", event.target);
            iptLog.value += `Serial port disconnected:\n${event.device.productName}\nPID ${event.device.productId} VID ${event.device.vendorId}\n\n`;
            iptLog.scrollTop = iptLog.scrollHeight; // 滚动到底部
        };

        // 清空数据接收窗口
        btnClear.onclick = () => {
            iptInput.value = "";
        };
    </script>
</body>
</html>